<?
/*! \brief Routes requests that are delivered through the frontend. 
 * 
 */
class IndexController extends FrontendController
{
	/*! \brief Default action. Start here.
	 * 
	 * Display the index view or forward us off to the formAction if there was 
	 * a requested method/service.
	 */
	public function indexAction()
	{	
		$slave = new Slave(HOST_NAME);
		$slave->getLocalLoad();
		if($this->_method)
			$this->_forward('form');
	}
	
	/*! \brief Display a form view of the requested method/service.
	 * 
	 * Instantiate a ServiceDojoForm for the requested service. Form submission 
	 * will return to this action, in which case we validate and forward off to 
	 * analyzeAction.
	 */
	public function formAction()
	{		
		$form = new ServiceDojoForm($this->_node, $this->_method);
				
		if ($this->getRequest()->isPost()) 
		{
			$formData = $this->getRequest()->getPost();
			if(!$form->isValid($formData))
				$form->populate($formData);
			else
				$this->_forward('analyze');
		}
		
		if($form != false)
			$this->view->form = $form;
	}
	
	/*! \brief POST everything to the backend and deal with the response.
	 * 
	 * Using Zend_Http_Client, POST everything from this request to the backend
	 * ServiceController. The backend returns either a description of the error 
	 * (xml), or an octet stream (md5 in content header).
	 */
	public function analyzeAction()
	{
		$client = new Zend_Http_Client($this->getRequest()->getPost('node').
			$this->getRequest()->getPost('method'));
		
		//set the POST
		$client->setParameterPost($this->getRequest()->getPost());
		
		//We need to POST all files to the backend. The frontend is really just 
		//for show-and-tell.
		foreach($_FILES as $key=>$value)
		{
			if($_FILES[$key]['size'] > 0 )
				$client->setFileUpload($_FILES[$key]['name'], $key, 
					file_get_contents($_FILES[$key]['tmp_name']));
		}
			
		//POST all this stuff to the backend and put the response body and mime
		//type into the view
		$response = $client->request('POST');
		
		$xml = new Xml();
		if($xml->setStringXml($response->getBody()) && $xml->getSimple()->xnrerr)
		{ 
			$this->view->error = true;
			$this->view->content =	'<br/>Command: '.$xml->getSimple()->command.
									'<br/><br/>Error Code: '.$xml->getSimple()->code.
									'<br/><br/>'.$xml->getSimple()->output;
		}
		else
		{
			$this->_helper->layout->disableLayout();
			$this->view->fname = $response->getHeader('fname');
			$this->view->exec = $response->getBody();
		}
	}
	
	//! \brief Displays licensing information
	public function licenseAction()
	{}
}
